package net.wicp.tams.component.services.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.ScopeConstants;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.ioc.annotations.Scope;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.apache.tapestry5.upload.services.MultipartDecoder;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.apache.tapestry5.util.TextStreamResponse;

import net.wicp.tams.common.web.PageAssist;
import net.wicp.tams.commons.Result;
import net.wicp.tams.commons.apiext.StringUtil;
import net.wicp.tams.commons.callback.IConvertValue;
import net.wicp.tams.commons.callback.impl.convertvalue.ConvertValueEnum;
import net.wicp.tams.component.SymbolConstantsCus;
import net.wicp.tams.component.components.Upload;
import net.wicp.tams.component.services.IReq;
import net.wicp.tams.component.services.ISupportedLocales;
import net.wicp.tams.component.tools.TapestryAssist;

@Scope(ScopeConstants.PERTHREAD)
public class ReqImpl implements IReq {

	private static final String paramName_allNum = "_findAllNum";// 设置记录总数的
																	// json域名
	@Inject
	private Messages messages;// 国际化
	@Inject
	private MultipartDecoder decoder;
	@Inject
	private Request request;
	@Inject
	protected RequestGlobals requestGlobals;
	@Inject
	@Symbol(SymbolConstantsCus.PATH_FILE_UPLOAD_DIR)
	private String defaultUploadDir;// 默认的文件上传目录,在service里配置
	@Inject
	@Symbol(SymbolConstants.CONTEXT_PATH)
	private String contextPath;// 默认的文件上传目录,在service里配置c
	@InjectService("locales")
	protected ISupportedLocales supportedLocales;

	private static String contextfilepath = null;
	private static File contextfileDir = null;
	private static File uploadDir = null;// 默认的文件上传目录

	@Override
	public List<File> saveUpload(File uploadDirParam) {
		File uploadDirTrue = (uploadDirParam == null || !uploadDirParam.exists()) ? getUploadDir() : uploadDirParam;
		List<File> retList = new ArrayList<File>();
		List<String> params = request.getParameterNames();
		for (String param : params) {
			if (param.startsWith(Upload.prefix)) {// 上传文件域
				UploadedFile uploadedFile = decoder.getFileUpload(param);
				System.out.println(uploadedFile.getFileName());
				// String exportFileName = Integer.toString(Math.abs(new
				// Random().nextInt()));
				File copied = new File(uploadDirTrue, uploadedFile.getFileName());// 文件名
																					// agentid_随机数_fileName
				uploadedFile.write(copied);
				retList.add(copied);
			}
		}
		return retList;
	}

	@Override
	public List<File> saveUpload() {
		return saveUpload(null);
	}

	@Override
	public List<File> saveUploadContext(String uploadPathFromContext) {
		File toDir = StringUtil.isNull(uploadPathFromContext) ? contextfileDir
				: new File(contextfilepath, uploadPathFromContext);
		if (!toDir.exists()) {
			toDir.mkdir();
		}
		return saveUpload(toDir);
	}

	@Override
	public String getContextFilePath() {
		if (contextfilepath == null) {
			contextfilepath = requestGlobals.getHTTPServletRequest().getSession().getServletContext().getRealPath("/");
		}
		return contextfilepath;
	}

	@Override
	public File getContextDir() {
		if (contextfileDir == null) {
			contextfileDir = new File(getContextFilePath());
			if (!contextfileDir.exists()) {
				contextfileDir.mkdir();
			}
		}
		return contextfileDir;
	}

	@Override
	public File getUploadDir() {
		String uploadDirPath = getContextFilePath() + File.separator + defaultUploadDir;
		if (uploadDir == null) {
			uploadDir = new File(uploadDirPath);
			if (!uploadDir.exists()) {
				uploadDir.mkdir();
			}
		}
		return uploadDir;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public IConvertValue<String> getEnumConvert(Class entityClass) {
		return new ConvertValueEnum(entityClass, supportedLocales.getCurLocale().getLanguage());
	}

	@Override
	public PageAssist buildPage() {
		String page = request.getParameter("page");
		String rows = request.getParameter("rows");
		String allNumStr = request.getParameter(paramName_allNum);
		int pageNo = StringUtil.isNull(page) ? 1 : Integer.parseInt(page);
		int rowsNum = StringUtil.isNull(rows) ? 10 : Integer.parseInt(rows);
		int allNum = StringUtil.isNull(allNumStr) ? -1 : Integer.parseInt(allNumStr);
		return new PageAssist(rowsNum, pageNo, allNum);
	}

	@Override
	public TextStreamResponse retSuccInfo() {
		return retSuccInfo(null);
	}

	@Override
	public TextStreamResponse retSuccInfo(String sucInfo) {
		Result retobj = Result.getSuc();
		sucInfo = StringUtil.isNull(sucInfo) ? messages.get("common.hint.success")
				: (messages.contains(sucInfo) ? messages.get(sucInfo) : sucInfo);
		retobj.setMessage(sucInfo);
		return TapestryAssist.getTextStreamResponse(retobj);
	}

	@Override
	public TextStreamResponse retErrorInfo(String errmsg) {
		return TapestryAssist.getTextStreamResponse(Result.getError(errmsg));
	}
}
